package com.jishuo.base.util;

import com.jishuo.base.bean.BaseResult;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtils 
{
	public static BaseResult xmltoList(String xml)
	{  
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new StringReader(xml));

			return  new BaseResult(iterateElement(document.getRootElement()));

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private static List<Map<String, Object>> iterateElement(Element element) {
		List<Map<String, Object>> retList = new ArrayList<>();
		List<Element> eles = element.elements();
		for (Element ele : eles) {
			Map<String, Object> map = new HashMap<>();
			for (Element ele1 : ele.elements()) {
				map.put(ele1.getName(), ele1.getText());
			}
			retList.add(map);
		}
		return retList;
	}

	public static void main(String[] args) {
		String xml = "<bills>"
						+"<bill>"
						+"<cantonid> 41</cantonid>"
						+"<cantoncode>130000</cantoncode>"
						+"<cantonname>河北省</cantonname>"
						+"</bill>"
						+"<bill>"
						+"<cantonid> 42</cantonid>"
						+"<cantoncode>130001</cantoncode>"
						+"<cantonname>石家庄</cantonname>"
						+"</bill>"
						+"<bill>"
						+"<cantonid> 43</cantonid>"
						+"<cantoncode>130002</cantoncode>"
						+"<cantonname>张家口</cantonname>"
						+"</bill>"
					+"</bills>";
		BaseResult result = xmltoList(xml);
		System.out.print("");
	}
}
